// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// M [author] rhyme_lph
// g [email]  rhymelph@gmail.com
// j [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/format/service_and_product_entity.dart';
import 'package:finance_app/src/entities/ocr_attachment_entity.dart';
import 'package:finance_app/src/entities/purchase_order_detail_entity.dart';
import 'package:finance_app/src/entities/quotation_detail_entity.dart';
import 'package:finance_app/src/entities/setting_data_entity.dart';
import 'package:finance_app/src/entities/transaction_entity.dart';
import 'package:finance_app/src/provider/dashboard/bill/new_bill_provider.dart';
import 'package:finance_app/src/provider/dashboard/contact/business_contact_detail_provider.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/utils/cash_utils.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/form_utils.dart';
import 'package:finance_app/src/utils/object_utils.dart';
import 'package:finance_app/src/widgets/button/normal_border_button.dart';
import 'package:finance_app/src/widgets/button/normal_popup_button.dart';
import 'package:finance_app/src/widgets/button/normal_text_button.dart';
import 'package:finance_app/src/widgets/common/tag_widget.dart';
import 'package:finance_app/src/widgets/form/add_form.dart';
import 'package:finance_app/src/widgets/form/form_edit_status_inherited_widget.dart';
import 'package:finance_app/src/widgets/form/price_form.dart';
import 'package:finance_app/src/widgets/form/status_line_form.dart';
import 'package:finance_app/src/widgets/form/value_select_form.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/form/attach_file_form.dart';
import 'package:finance_app/src/widgets/form/service_and_product_form_item.dart';
import 'package:finance_app/src/widgets/input/form_input_field.dart';
import 'package:finance_app/src/widgets/form/text_area_input_form.dart';
import 'package:finance_app/src/widgets/wrapper/normal_form_wrapper.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/dashboard/purchase/new_purchase_order_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:flutter/services.dart';
import 'package:tuple/tuple.dart';

@RouterMeta(paramName: "newPurchaseOrderPage")
class NewPurchaseOrderPage extends StatefulWidget {
  final TransactionEntity data;
  final QuotationDetailEntity generate;
  final bool isSelectMode;

  const NewPurchaseOrderPage(
      {Key key, this.data, this.generate, this.isSelectMode})
      : super(key: key);

  @override
  _NewPurchaseOrderPageState createState() => _NewPurchaseOrderPageState();
}

class _NewPurchaseOrderPageState extends State<NewPurchaseOrderPage>
    with PagePresenter<NewPurchaseOrderPage, NewPurchaseOrderProvider> {
  String get title => provider.data == null && pageStatus != PageStatus.loading
      ? S.current.new_purchase_order
      : provider.isEdit == true
          ? S.current.edit_purchase_order
          : S.current.purchase_order;

  Widget get rightButton => listBuilder<bool>(
        selector: (_, __) => __.isEdit == false && __.data != null,
        builder: (BuildContext context, bool value, Widget child) =>
            value ? _buildPopButton() : _buildSaveBtn(),
      );

  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
          titleWidget: listBuilder<Tuple2<PurchaseOrderDetailEntity, bool>>(
            selector: (_, __) => Tuple2(__.data, __.isEdit),
            builder: (BuildContext context,
                    Tuple2<PurchaseOrderDetailEntity, bool> value,
                    Widget child) =>
                Text(title),
          ),
          actions: [
            rightButton,
          ]);

  Widget _buildPopButton() => listBuilder<Tuple2<bool, List<String>>>(
        selector: (_, __) => Tuple2<bool, List<String>>(__.isEdit, __.menuList),
        builder: (BuildContext context, Tuple2<bool, List<String>> value,
                Widget child) =>
            value.item1 == false
                ? NormalMorePopupButton(
                    onSelect: provider.onSelectMenu,
                    menuList: value.item2,
                  )
                : _buildSaveBtn(),
      );

  Widget _buildSaveBtn() {
    return listBuilder<bool>(
      selector: (_, __) => pageStatus != PageStatus.loading,
      builder: (BuildContext context, bool value, Widget child) => value == true
          ? NormalSaveTextButton(
              onTap: provider.onSave,
            )
          : Container(),
    );
  }

  @override
  void initState() {
    provider.isSelectMode = widget.isSelectMode;
    provider.currency = Config.defaultCurrency;
    provider.deliveryAddress = Config.currentCompany.deliveryAddressLine1;
    provider.postalCodeController.text =
        Config.currentCompany.deliveryAddressPostalCode ?? '';
    provider.unitNumberController.text =
        Config.currentCompany.deliveryAddressUnit ?? '';
    final pro = Providers.get<BusinessContactDetailProvider>(
        RouterGenProviders.businessContactDetailPage, null);
    if (pro != null) {
      provider.supplier = pro.contact;
    }
    final billProvider =
        Providers.get<NewBillProvider>(RouterGenProviders.newBillPage, null);
    if (billProvider != null) {
      provider.supplier = billProvider.supplier;
    }
    provider.init(widget.data?.transactionableId);
    provider.initGenerate(widget.generate);
    super.initState();
  }

  Widget buildSaveBtn() {
    return listBuilder<bool>(
      selector: (_, __) => pageStatus != PageStatus.loading,
      builder: (BuildContext context, bool value, Widget child) => value == true
          ? NormalSaveTextButton(
              onTap: provider.onSave,
            )
          : Container(),
    );
  }

  @override
  Widget wrapperBody(Widget child) {
    return listBuilder<bool>(
      selector: (_, __) => __.isEdit == true || provider.id == null,
      builder: (BuildContext context, bool value, Widget child) =>
          FormEditStatusInheritedWidget(
        isEdit: value,
        child: child,
      ),
      child: child,
    );
  }

  @override
  Widget get buildWidget => ColoredBox(
        color: Colors.white,
        child: ListView(
          children: [
            listBuilder<String>(
              selector: (_, __) => __.data?.status,
              builder: (BuildContext context, String value, Widget child) =>
                  StatusLineForm(
                status: value,
                model: ReimburseModel.purchaseOrder,
              ),
            ),
            listBuilder<String>(
              selector: (_, __) => __.supplier?.name,
              builder: (BuildContext context, String value, Widget child) =>
                  ValueSelectForm(
                title: S.current.supplier_name,
                onTap: provider.onChangeSupplierName,
                value: value,
              ),
            ),
            Stack(
              children: [
                listBuilder<bool>(
                  selector: (_, __) => __.numberHasError,
                  builder: (BuildContext context, bool value, Widget child) =>
                      FromInputField(
                    controller: provider.poNumberController,
                    focusNode: provider.poNumberFocusNode,
                    tip: S.current.po_number,
                    hasError: value,
                  ),
                ),
                Align(
                  alignment: Alignment.centerRight,
                  child: listBuilder<bool>(
                    selector: (_, __) =>
                        __.isDelivered || __.data?.status == 'closed',
                    builder: (BuildContext context, bool value, Widget child) =>
                        value == true
                            ? Container(
                                margin: EdgeInsets.only(
                                    right: getDp(35), top: getDp(20)),
                                child: BlueTagWidget(
                                  content: S.current.delivered,
                                ),
                              )
                            : Container(),
                  ),
                )
              ],
            ),
            listBuilder<DateTime>(
              selector: (_, __) => __.date,
              builder: (BuildContext context, DateTime value, Widget child) =>
                  ValueSelectForm(
                title: S.current.issue_date,
                value: ObjectUtils.isNullDefaultFormat<DateTime>(value, null,
                    (data) => DateTimeUtils.formatGlobalDateTime(data)),
                onTap: provider.onChangeIssueDate,
              ),
            ),
            listBuilder<DateTime>(
              selector: (_, __) => __.deliveryDate,
              builder: (BuildContext context, DateTime value, Widget child) =>
                  ValueSelectForm(
                title: S.current.delivery_date,
                value: ObjectUtils.isNullDefaultFormat<DateTime>(value, null,
                    (data) => DateTimeUtils.formatGlobalDateTime(data)),
                onTap: provider.onChangeDeliveryDate,
              ),
            ),
            listBuilder<String>(
              selector: (_, __) => __.deliveryAddress,
              builder: (BuildContext context, String value, Widget child) =>
                  ValueSelectForm(
                title: S.current.delivery_address,
                value: value,
                onTap: provider.onChangeDeliveryAddress,
              ),
            ),
            FromInputField(
              controller: provider.unitNumberController,
              focusNode: provider.unitNumberFocusNode,
              tip: S.current.unit_number,
            ),
            FromInputField(
              controller: provider.postalCodeController,
              focusNode: provider.postalCodeFocusNode,
              tip: S.current.postal_code,
              keyboardType: TextInputType.number,
              inputFormatterList: [
                FilteringTextInputFormatter.digitsOnly,
              ],
            ),
            listBuilder<String>(
              selector: (_, __) => __.currency?.name,
              builder: (BuildContext context, String value, Widget child) =>
                  ValueSelectForm(
                title: S.current.currency,
                value: value,
                onTap: provider.onChangeCurrency,
                border: null,
              ),
            ),
            AppSpaces.grayH6,
            listBuilder<int>(
              selector: (_, __) =>
                  List<ServiceAndProductEntity>.from(__.serviceAndProductList)
                      .length,
              builder: (BuildContext context, int value, Widget child) =>
                  value != 0
                      ? Column(
                          children: [
                            // AppSpaces.grayH6,
                            ...List.generate(
                                value,
                                (index) => listBuilder<
                                        Tuple4<ServiceAndProductEntity, int,
                                            num, SettingDataTax>>(
                                      selector: (_, __) => Tuple4(
                                          __.serviceAndProductList[index],
                                          __.serviceAndProductList[index]
                                              .number,
                                          __.serviceAndProductList[index]
                                              .discountedAmount,
                                          __.serviceAndProductList[index].tax),
                                      builder: (BuildContext context,
                                              Tuple4<ServiceAndProductEntity,
                                                      int, num, SettingDataTax>
                                                  value,
                                              Widget child) =>
                                          ServiceAndProductFormItem(
                                        onTap: () =>
                                            provider.onSelectItem(value.item1),
                                        productEntity: value.item1,
                                        hasError: false,
                                        showHeader: index == 0,
                                        isLastElement: provider
                                                    .serviceAndProductList
                                                    .length ==
                                                index + 1 &&
                                            provider.id != null &&
                                            provider.isEdit == false,
                                      ),
                                    ))
                          ],
                        )
                      : ValueSelectForm(
                          title: S.current.item__quantity__amount__tax_rate,
                          onTap: provider.onAddItem,
                        ),
            ),
            AddForm(
              title: S.current.add_item,
              onTap: provider.onAddItem,
            ),
            AppSpaces.grayH6,
            NormalFormWrapper(
              child: Column(
                children: [
                  // buildSubTotal(),
                  // SizedBox(
                  //   height: getDp(25),
                  // ),
                  // _buildGst(),
                  _buildTotal(),
                  _buildIncludes(),
                ],
              ),
            ),
            AppSpaces.grayH6,
            TextAreaInputForm(
              title: S.current.additional_notes_optional,
              controller: provider.notesController,
              focusNode: provider.notesFocusNode,
            ),
            NormalFormWrapper(
              child:
                  listBuilder<Tuple2<List<String>, List<OcrAttachmentEntity>>>(
                selector: (_, __) => Tuple2(
                    List.from(__.files), List.from(__.attachments ?? [])),
                builder: (BuildContext context,
                        Tuple2<List<String>, List<OcrAttachmentEntity>> value,
                        Widget child) =>
                    AttachFileForm(
                  onAdd: provider.onAddAttachment,
                  files: value.item1,
                  onSelectFile: provider.onSelectFile,
                  attachments: value.item2,
                  onSelectAttachment: provider.onSelectAttachment,
                ),
              ),
            ),
            FormStatusWidget(
              enable: Container(),
              disable: listBuilder<Tuple2<bool, dynamic>>(
                selector: (_, __) =>
                    Tuple2(__.menuList.contains("See Bill"), __.data?.billId),
                builder: (BuildContext context, Tuple2<bool, dynamic> value,
                        Widget child) =>
                    value.item1 == true
                        ? Column(
                            children: [
                              if (value.item2 != null) ...[
                                NormalBorderButton(
                                  title: S.current.see_bill,
                                  onTap: provider.onSeeBill,
                                  isFit: true,
                                ),
                                AppSpaces.h30,
                              ] else ...[
                                NormalBorderButton(
                                  title: S.current.convert_to_bill,
                                  onTap: provider.onConvertToBill,
                                  isFit: true,
                                ),
                                AppSpaces.h30,
                                NormalBorderButton(
                                  title: S.current.make_a_copy,
                                  onTap: provider.onMakeACopy,
                                  isFit: true,
                                ),
                                AppSpaces.h30,
                              ]
                            ],
                          )
                        : Container(),
              ),
            )
          ],
        ),
      );

  Widget buildSubTotal() {
    return listBuilder<double>(
      selector: (_, __) => __.subTotal,
      builder: (BuildContext context, double value, Widget child) => PriceForm(
        title: S.current.subtotal,
        amount: CashUtils.formatCashAmount(value),
      ),
    );
  }

  Widget _buildGst() {
    return listBuilder<double>(
      selector: (_, __) => __.gst,
      builder: (BuildContext context, double value, Widget child) =>
          value == 0.00
              ? Container()
              : Padding(
                  padding: EdgeInsets.only(bottom: getDp(25)),
                  child: PriceForm(
                    title: S.current.gst,
                    amount: CashUtils.formatCashAmount(value),
                  ),
                ),
    );
  }

  Widget _buildTotal() {
    return listBuilder<double>(
      selector: (_, __) => __.total,
      builder: (BuildContext context, double value, Widget child) => PriceForm(
        title: S.current.total,
        amount: CashUtils.formatCashAmount(value),
      ),
    );
  }

  Widget _buildIncludes() {
    return Align(
      alignment: Alignment.centerRight,
      child: listBuilder<double>(
          builder: (BuildContext context, double value, Widget child) =>
              Config.currentCompany.enableGst == 0
                  ? Container()
                  : Container(
                      padding: EdgeInsets.only(top: 2),
                      child: Text(
                        '${S.current.includes_gst} ${CashUtils.formatCashAmount(value)}',
                        style: TextStyle(
                          color: aceDarkGrayColor,
                          fontSize: getSp(14),
                          fontWeight: FontWeight.w400,
                          height: 1,
                        ),
                      ),
                    ),
          selector: (_, __) => __.includesGST + __.gst),
    );
  }
}
